
#include <fastdds/dds/domain/DomainParticipantFactory.hpp>
#include <fastdds/dds/subscriber/qos/DataReaderQos.hpp>
#include <fastdds/dds/subscriber/SampleInfo.hpp>
#include <fastdds/rtps/transport/TCPv4TransportDescriptor.h>
#include <fastdds/rtps/transport/UDPv4TransportDescriptor.h>
#include <fastdds/rtps/transport/TCPv6TransportDescriptor.h>
#include <fastdds/rtps/transport/UDPv6TransportDescriptor.h>
#include <fastrtps/utils/IPLocator.h>

#include <thread>
#include <chrono>

#include "zeroCopyPublisher.hpp"

using namespace std;
using namespace eprosima::fastdds::dds;
using namespace eprosima::fastdds::rtps;

std::array<char,10240> g_sBuffer;
std::array<char,1048576> g_mBuffer;
std::array<char,10485760> g_fullBuffer;

zeroCopyPublisher::zeroCopyPublisher()
    : m_testStartTime(std::chrono::system_clock::now())
    , m_bBenchmarkFinished(false)
    , m_iTickTime(100)
    , m_iSize(0)
    , m_vSamples(nullptr)
    , m_iSamplesCount(0)
    , mp_participant(nullptr)
    , mp_publisher(nullptr)
    , mp_writer(nullptr)
    , mp_topic_pub(nullptr)
    , m_pubListener(this)
    , m_type(new messDataPubSubType())
    , m_typeSmall(new smallDataPubSubType())
    , m_typeMedium(new mediumDataPubSubType())
    , m_typeBig(new bigDataPubSubType())
{
    m_iCount = 0;
    g_sBuffer.fill(255);
    g_mBuffer.fill(255);
    g_fullBuffer.fill(255);
}

bool zeroCopyPublisher::init(
        int transport,
        ReliabilityQosPolicyKind reliabilityKind,
        int data_size,
        int tick_time,
        const std::string& topicName,
        int domain,
        int loan,
        int size)
{
    m_iTestSize = data_size;//MB
    m_iTickTime = tick_time;
    m_iSize = size;
    m_iLoan = loan;
    memset(m_vSamples, 0, sizeof(int) * m_iSamplesSize);
    m_iSamplesCount = 0;

    switch (m_iSize)
    {
        default:
        case 0:
            m_Hello.index(0);
            m_iSamplesCount = 1;
            break;
        case 1:
            m_HelloSmall.index(0);
            m_iSamplesCount = ((m_iTestSize*1024)/10);//k/k
            break;
        case 2:
            m_HelloMedium.index(0);
            m_iSamplesCount = ((m_iTestSize*1024)/1024);
            break;
        case 3:
            m_HelloBig.index(0);
            m_iSamplesCount = ((m_iTestSize*1024)/10240);
            break;
    }

    //CREATE THE PARTICIPANT
    DomainParticipantQos pqos;
    // pqos.wire_protocol().builtin.discovery_config.leaseDuration = eprosima::fastrtps::c_TimeInfinite;
    // pqos.wire_protocol().builtin.discovery_config.leaseDuration_announcementperiod = Duration_t(1, 0);
    pqos.name("Participant_pub");

    if (transport == 1)
    {
        pqos.transport().use_builtin_transports = true;
    }
    else if (transport == 2)
    {
        pqos.transport().use_builtin_transports = false;

        std::shared_ptr<TCPv4TransportDescriptor> descriptor = std::make_shared<TCPv4TransportDescriptor>();
        descriptor->sendBufferSize = 8912896; // 8.5Mb
        descriptor->receiveBufferSize = 8912896; // 8.5Mb
        descriptor->add_listener_port(5100);
        pqos.transport().user_transports.push_back(descriptor);
    }
    else if (transport == 3)
    {
        //uint32_t kind = LOCATOR_KIND_UDPv6;
    }
    else if (transport == 4)
    {
        pqos.transport().use_builtin_transports = false;

        std::shared_ptr<TCPv6TransportDescriptor> descriptor = std::make_shared<TCPv6TransportDescriptor>();
        descriptor->sendBufferSize = 8912896; // 8.5Mb
        descriptor->receiveBufferSize = 8912896; // 8.5Mb
        descriptor->add_listener_port(5100);
        pqos.transport().user_transports.push_back(descriptor);
    }

    mp_participant = DomainParticipantFactory::get_instance()->create_participant(domain, pqos);

    if (mp_participant == nullptr)
    {
        return false;
    }

    //REGISTER THE TYPE
    std::string data_type;
    switch (m_iSize)
    {
        default:
        case 0:
            data_type = "messData";
            m_type.register_type(mp_participant);
            break;
        case 1:
            data_type = "smallData";
            m_typeSmall.register_type(mp_participant);
            break;
        case 2:
            data_type = "mediumData";
            m_typeMedium.register_type(mp_participant);
            break;
        case 3:
            data_type = "bigData";
            m_typeBig.register_type(mp_participant);
            break;
    }

    //CREATE THE PUBLISHER
    mp_publisher = mp_participant->create_publisher(PUBLISHER_QOS_DEFAULT);

    if (mp_publisher == nullptr)
    {
        return false;
    }

    //CREATE THE TOPIC
    mp_topic_pub = mp_participant->create_topic(topicName, data_type, TOPIC_QOS_DEFAULT);

    if (mp_topic_pub == nullptr)
    {
        return false;
    }

    //CREATE THE DATAWRITER
    DataWriterQos wqos;
    wqos.history().kind = KEEP_LAST_HISTORY_QOS;
    wqos.history().depth = 100;
    wqos.resource_limits().max_samples = 500;
    wqos.resource_limits().allocated_samples = 200;
    wqos.reliable_writer_qos().times.heartbeatPeriod.seconds = 2;
    wqos.reliable_writer_qos().times.heartbeatPeriod.nanosec = 200 * 1000 * 1000;
    wqos.reliability().kind = reliabilityKind;
    wqos.publish_mode().kind = ASYNCHRONOUS_PUBLISH_MODE;

    wqos.durability().kind = VOLATILE_DURABILITY_QOS;
    wqos.data_sharing().automatic();

    mp_writer = mp_publisher->create_datawriter(mp_topic_pub, wqos, &m_pubListener);

    if (mp_writer == nullptr)
    {
        return false;
    }

    
    return true;
}

zeroCopyPublisher::~zeroCopyPublisher()
{
    if (m_vSamples != nullptr)
    {
        delete(m_vSamples);
        m_vSamples = nullptr;
    }
    if (mp_writer != nullptr)
    {
        mp_publisher->delete_datawriter(mp_writer);
    }
    if (mp_publisher != nullptr)
    {
        mp_participant->delete_publisher(mp_publisher);
    }
    if (mp_topic_pub != nullptr)
    {
        mp_participant->delete_topic(mp_topic_pub);
    }
    DomainParticipantFactory::get_instance()->delete_participant(mp_participant);
}


zeroCopyPublisher::PubListener::PubListener(
        zeroCopyPublisher* parent)
    : mParent(parent)
    , matched_(0)
{
}

void zeroCopyPublisher::PubListener::on_publication_matched(
        eprosima::fastdds::dds::DataWriter*,
        const eprosima::fastdds::dds::PublicationMatchedStatus& info)
{
    if (info.current_count_change == 1)
    {
        std::cout << "Publisher matched. Test starts..." << std::endl;
        if (matched_ == 0)
        {
            mParent->m_testStartTime = std::chrono::system_clock::now();
        }
        matched_++;
    }
    else if (info.current_count_change == -1)
    {
        mParent->m_bBenchmarkFinished = true;
        std::cout << "Publisher unmatched. Test Aborted" << std::endl;
    }
    else
    {
        std::cout << info.current_count_change
                  << " is not a valid value for PublicationMatchedStatus current count change" << std::endl;
    }
}


void zeroCopyPublisher::run()
{
    qlog_i("LoanData DataWriter waiting for DataReaders.");
    struct  timeval   tv_begin,tv_end,val;
    unsigned long diff;
    const unsigned long Converter = 1000 * 1000; // 1s == 1000 * 1000 us
    static int msgsent = 0;
    char ch = 'y';
    int g_ilimit = 0;
    std::chrono::milliseconds ms;
    do
    {
        while (m_pubListener.matched_ == 0)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(250)); // Sleep 250 ms
        }
        if (ch == 'y')
        {
            if( m_iLoan > 0) {

                msgsent = -1;
                switch (m_iSize)
                {
                    case 0:
                        {
                            void* sample = nullptr;
                            messData* data = nullptr;
                            gettimeofday(&tv_begin,NULL);
                            qlog_i("start: sec --- %ld, usec --- %ld\n", tv_begin.tv_sec, tv_begin.tv_usec);
                            g_ilimit = m_iSamplesCount;
                            while(g_ilimit--)
                            {
                            if (ReturnCode_t::RETCODE_OK == mp_writer->loan_sample(sample))
                                {
                                    qlog_i("Preparing sample at address %#x",sample);
                                    data = static_cast<messData*>(sample);
                                    data->index() = msgsent + 1;
                                    data->maxLimit() = m_iSamplesCount;
                                    // memcpy(data->message().data(), "LoanableHelloWorld ", 20);
                                    // ms = std::chrono::duration_cast< std::chrono::milliseconds >(
                                    //     std::chrono::system_clock::now().time_since_epoch()
                                    // );
                                    gettimeofday(&val,NULL);
                                    data->timeSec() = val.tv_sec;
                                    data->timeuSec() = val.tv_usec;
                                    if(g_ilimit == 0){
                                        data->header() = 0xa5;
                                    }else{
                                        data->header() = 0x00;
                                    }
                                    mp_writer->write(sample);
                                    ++msgsent;
                                } 
                            }
                            

                            gettimeofday(&tv_end,NULL);
                            qlog_i("end: sec --- %ld, usec --- %ld\n", tv_end.tv_sec, tv_end.tv_usec);
                            diff = (tv_end.tv_sec * Converter + tv_end.tv_usec) - (tv_begin.tv_sec * Converter + tv_begin.tv_usec);
                            qlog_i("diff:---%ld  sec --- %ld, usec --- %ld\n", diff, diff / Converter, diff % Converter);

                            
                            qlog_i("Sending sample, count=%d, send another sample?(y-yes,n-stop): ", msgsent);
                        }
                        
                    break;
                    case 1:
                        {
                            void* sample = nullptr;
                            smallData* data = nullptr;
                            gettimeofday(&tv_begin,NULL);
                            qlog_i("start: sec --- %ld, usec --- %ld\n", tv_begin.tv_sec, tv_begin.tv_usec);
                            g_ilimit = m_iSamplesCount;
                            while(g_ilimit--)
                            {
                                if (ReturnCode_t::RETCODE_OK == mp_writer->loan_sample(sample))
                                {
                                    qlog_i("Preparing sample at address %#x",sample);
                                    data = static_cast<smallData*>(sample);
                                    data->index() = msgsent + 1;
                                    // memcpy(data->message().data(), "LoanableHelloWorld ", 20);
                                    g_sBuffer[0] = msgsent + 1;
                                    data->data(g_sBuffer);
                                    data->maxLimit() = m_iSamplesCount;
                                    gettimeofday(&val,NULL);
                                    data->timeSec() = val.tv_sec;
                                    data->timeuSec() = val.tv_usec;
                                    if(g_ilimit == 0){
                                        data->header() = 0xa5;
                                    }else{
                                        data->header() = 0x00;
                                    }
                                    mp_writer->write(sample);
                                    ++msgsent;
                                    std::this_thread::sleep_for(std::chrono::milliseconds(m_iTickTime));
                                }
                            }

                            gettimeofday(&tv_end,NULL);
                            qlog_i("end: sec --- %ld, usec --- %ld\n", tv_end.tv_sec, tv_end.tv_usec);
                            diff = (tv_end.tv_sec * Converter + tv_end.tv_usec) - (tv_begin.tv_sec * Converter + tv_begin.tv_usec);
                            qlog_i("diff:---%ld  sec --- %ld, usec --- %ld\n", diff, diff / Converter, diff % Converter);

                            double g_dSSpeed = (double)((double)(1*Converter*m_iSamplesCount/diff)/1024);
                            qlog_i("SMALL SEND SPEED:%0.2fM/s",g_dSSpeed);
                            qlog_i("Sending sample, count=%d, send another sample?(y-yes,n-stop): ", msgsent);
                        }
                        
                    break;
                    case 2:
                        {
                            void* sample = nullptr;
                            mediumData* data=nullptr;
                            gettimeofday(&tv_begin,NULL);
                            qlog_i("start: sec --- %ld, usec --- %ld\n", tv_begin.tv_sec, tv_begin.tv_usec);
                            g_ilimit = m_iSamplesCount;
                            while(g_ilimit--)
                            {
                                if (ReturnCode_t::RETCODE_OK == mp_writer->loan_sample(sample))
                                {
                                    qlog_i("Preparing sample at address %#x",sample);
                                    data = static_cast<mediumData*>(sample);
                                    data->index() = msgsent + 1;
                                    // memcpy(data->message().data(), "LoanableHelloWorld ", 20);
                                    data->maxLimit() = m_iSamplesCount;
                                    g_mBuffer[0] = msgsent + 1;
                                    data->data(g_mBuffer);
                                    gettimeofday(&val,NULL);
                                    data->timeSec() = val.tv_sec;
                                    data->timeuSec() = val.tv_usec;
                                    if(g_ilimit == 0){
                                        data->header() = 0xa5;
                                    }else{
                                        data->header() = 0x00;
                                    }
                                    mp_writer->write(sample);
                                    ++msgsent;
                                    std::this_thread::sleep_for(std::chrono::milliseconds(m_iTickTime));
                                }
                                
                            }

                            gettimeofday(&tv_end,NULL);
                            qlog_i(" end: sec --- %ld, usec --- %ld\n", tv_end.tv_sec, tv_end.tv_usec);
                            diff = (tv_end.tv_sec * Converter + tv_end.tv_usec) - (tv_begin.tv_sec * Converter + tv_begin.tv_usec);
                            qlog_i("diff:---%ld  sec --- %ld, usec --- %ld\n", diff, diff / Converter, diff % Converter);
                            double g_dSSpeed = (double)(1*Converter*m_iSamplesCount/diff);
                            qlog_i("MEDIUM SEND SPEED:%0.2fM/s",g_dSSpeed);
                            qlog_i("Sending sample, count=%d, send another sample?(y-yes,n-stop): ", msgsent);
                        }
                        
                    break;

                    case 3:
                        {
                            void* sample = nullptr;
                            bigData* data = nullptr;
                            gettimeofday(&tv_begin,NULL);
                            qlog_i(" start: sec --- %ld, usec --- %ld\n", tv_begin.tv_sec, tv_begin.tv_usec);
                            g_ilimit = m_iSamplesCount;
                            while(g_ilimit--)
                            {
                                if (ReturnCode_t::RETCODE_OK == mp_writer->loan_sample(sample))
                                {
                                    qlog_i("Preparing sample at address %#x",sample);
                                    data = static_cast<bigData*>(sample);
                                    data->index() = msgsent + 1;
                                    // memcpy(data->message().data(), "LoanableHelloWorld ", 20);
                                    data->maxLimit() = m_iSamplesCount;
                                    g_fullBuffer[0] = msgsent + 1;
                                    data->data(g_fullBuffer);

                                    gettimeofday(&val,NULL);
                                    data->timeSec() = val.tv_sec;
                                    data->timeuSec() = val.tv_usec;
                                    if(g_ilimit == 0){
                                        data->header() = 0xa5;
                                    }else{
                                        data->header() = 0x00;
                                    }
                                    mp_writer->write(sample);
                                    ++msgsent;
                                    std::this_thread::sleep_for(std::chrono::milliseconds(m_iTickTime));
                                }
                            }
                            gettimeofday(&tv_end,NULL);
                            qlog_i(" end: sec --- %ld, usec --- %ld\n", tv_end.tv_sec, tv_end.tv_usec);
                            diff = (tv_end.tv_sec * Converter + tv_end.tv_usec) - (tv_begin.tv_sec * Converter + tv_begin.tv_usec);
                            qlog_i("diff:---%ld  sec --- %ld, usec --- %ld\n", diff, diff / Converter, diff % Converter);
                            double g_dSSpeed = (double)(10*Converter*m_iSamplesCount/diff);
                            qlog_i("BIG SEND SPEED:%0.2fM/s",g_dSSpeed);
                            qlog_i("Sending sample, count=%d, send another sample?(y-yes,n-stop): ", msgsent);
                        }

                    break;
                }
            } else {
                publish();
            }
        }
        else if (ch == 'n')
        {
            qlog_i("Stopping execution ");
            break;
        }
        else
        {
            qlog_i("Command %s, not recognized, please enter \"y/n\":",ch);
        }
    } while (std::cin >> ch);

}

bool zeroCopyPublisher::publish()
{
    struct  timeval   tv_begin,tv_end,val;
    unsigned long diff;
    const unsigned long Converter = 1000 * 1000; // 1s == 1000 * 1000 us
    int msgsent = 0;
    int g_ilimit = 0;
    gettimeofday(&tv_begin,NULL);
    qlog_i("no loan start: sec --- %ld, usec --- %ld\n", tv_begin.tv_sec, tv_begin.tv_usec);
    g_ilimit = m_iSamplesCount;
    msgsent = -1;
    if (m_pubListener.matched_ > 0)
    {
        switch (m_iSize)
        {
            default:
            case 0:
            {
                while(g_ilimit--)
                {
                    m_Hello.index() = msgsent + 1;
                    m_Hello.maxLimit() = m_iSamplesCount;
                    mp_writer->write((void*)&m_Hello);
                    gettimeofday(&val,NULL);
                    m_Hello.timeSec() = val.tv_sec;
                    m_Hello.timeuSec() = val.tv_usec;
                    if(g_ilimit == 0){
                        m_Hello.header() = 0xa5;
                    }else{
                        m_Hello.header() = 0x00;
                    }
                    msgsent++;
                    std::this_thread::sleep_for(std::chrono::milliseconds(m_iTickTime));
                }
                gettimeofday(&tv_end,NULL);
                qlog_i("----------------------------------------------------");
                qlog_i("no loan end: sec --- %ld, usec --- %ld", tv_end.tv_sec, tv_end.tv_usec);
                diff = (tv_end.tv_sec * Converter + tv_end.tv_usec) - (tv_begin.tv_sec * Converter + tv_begin.tv_usec);
                qlog_i("no loan diff:---%ld  sec --- %ld, usec --- %ld", diff, diff / Converter, diff % Converter);

                double g_dSSpeed = (double)((double)(1*Converter*m_iSamplesCount/diff)/1024);
                qlog_i("no loan SEND SPEED:%0.2fM/s",g_dSSpeed);
                qlog_i("----------------------------------------------------");
                qlog_i("Sending sample, count=%d, send another sample?(y-yes,n-stop): ", msgsent);
                return true;
            }
            case 1:
            {
                while(g_ilimit--)
                {
                    m_HelloSmall.index() = msgsent + 1;
                    // memcpy(data->message().data(), "LoanableHelloWorld ", 20);
                    m_HelloSmall.maxLimit() = m_iSamplesCount;
                    g_sBuffer[0] = msgsent + 1;
                    m_HelloSmall.data(g_sBuffer);

                    gettimeofday(&val,NULL);
                    m_HelloSmall.timeSec() = val.tv_sec;
                    m_HelloSmall.timeuSec() = val.tv_usec;
                    if(g_ilimit == 0){
                        m_HelloSmall.header() = 0xa5;
                    }else{
                        m_HelloSmall.header() = 0x00;
                    }
                    mp_writer->write((void*)&m_HelloSmall);
                    msgsent++;
                    std::this_thread::sleep_for(std::chrono::milliseconds(m_iTickTime));
                }
                gettimeofday(&tv_end,NULL);
                qlog_i("----------------------------------------------------");
                qlog_i("no loan end: sec --- %ld, usec --- %ld", tv_end.tv_sec, tv_end.tv_usec);
                diff = (tv_end.tv_sec * Converter + tv_end.tv_usec) - (tv_begin.tv_sec * Converter + tv_begin.tv_usec);
                qlog_i("no loan diff:---%ld  sec --- %ld, usec --- %ld", diff, diff / Converter, diff % Converter);

                double g_dSSpeed = (double)((double)(1*Converter*m_iSamplesCount/diff)/1024);
                qlog_i("no loan SMALL SEND SPEED:%0.2fM/s",g_dSSpeed);
                qlog_i("----------------------------------------------------");
                qlog_i("Sending sample, count=%d, send another sample?(y-yes,n-stop): ", msgsent);
                return true;
            }
            case 2:
            {
                while(g_ilimit--)
                {
                    m_HelloMedium.index() = msgsent + 1;
                    // memcpy(data->message().data(), "LoanableHelloWorld ", 20);
                    m_HelloMedium.maxLimit() = m_iSamplesCount;
                    g_mBuffer[0] = msgsent + 1;
                    m_HelloMedium.data(g_mBuffer);

                    gettimeofday(&val,NULL);
                    m_HelloMedium.timeSec() = val.tv_sec;
                    m_HelloMedium.timeuSec() = val.tv_usec;
                    if(g_ilimit == 0){
                        m_HelloMedium.header() = 0xa5;
                    }else{
                        m_HelloMedium.header() = 0x00;
                    }
                    mp_writer->write((void*)&m_HelloMedium);
                    msgsent++;
                    std::this_thread::sleep_for(std::chrono::milliseconds(m_iTickTime));
                }
                gettimeofday(&tv_end,NULL);
                qlog_i("----------------------------------------------------");
                qlog_i("no loan end: sec --- %ld, usec --- %ld", tv_end.tv_sec, tv_end.tv_usec);
                diff = (tv_end.tv_sec * Converter + tv_end.tv_usec) - (tv_begin.tv_sec * Converter + tv_begin.tv_usec);
                qlog_i("no loan diff:---%ld  sec --- %ld, usec --- %ld", diff, diff / Converter, diff % Converter);
                double g_dSSpeed = (double)(1*Converter*m_iSamplesCount/diff);
                qlog_i("no loan MEDIUM SEND SPEED:%0.2fM/s",g_dSSpeed);
                qlog_i("----------------------------------------------------");
                qlog_i("Sending sample, count=%d, send another sample?(y-yes,n-stop): ", msgsent);
                return true;
            }
            case 3:
            {
                while(g_ilimit--)
                {
                    m_HelloBig.index() = msgsent + 1;
                    // memcpy(data->message().data(), "LoanableHelloWorld ", 20);
                    m_HelloBig.maxLimit() = m_iSamplesCount;
                    g_fullBuffer[0] = msgsent + 1;
                    m_HelloBig.data(g_fullBuffer);

                    gettimeofday(&val,NULL);
                    m_HelloBig.timeSec() = val.tv_sec;
                    m_HelloBig.timeuSec() = val.tv_usec;
                    if(g_ilimit == 0){
                        m_HelloBig.header() = 0xa5;
                    }else{
                        m_HelloBig.header() = 0x00;
                    }
                    mp_writer->write((void*)&m_HelloBig);
                    msgsent++;
                    std::this_thread::sleep_for(std::chrono::milliseconds(m_iTickTime));
                }
                gettimeofday(&tv_end,NULL);
                qlog_i("----------------------------------------------------");
                qlog_i("no loan end: sec --- %ld, usec --- %ld", tv_end.tv_sec, tv_end.tv_usec);
                diff = (tv_end.tv_sec * Converter + tv_end.tv_usec) - (tv_begin.tv_sec * Converter + tv_begin.tv_usec);
                qlog_i("no loan diff:---%ld  sec --- %ld, usec --- %ld", diff, diff / Converter, diff % Converter);
                double g_dSSpeed = (double)(10*Converter*m_iSamplesCount/diff);
                qlog_i("no loan BIG SEND SPEED:%0.2fM/s",g_dSSpeed);
                qlog_i("----------------------------------------------------");
                qlog_i("Sending sample, count=%d, send another sample?(y-yes,n-stop): ", msgsent);
                return true;
            }
        }
    }
    return false;
}
